import _axios from 'axios'
import common from '@/components/common'

_axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

const axios = _axios.create({
  baseURL: 'http://localhost:9001',
  timeout: 10000,
  withCredentials: true
})

const methods = {
  axios: axios,
  async get (url, param, app, callback) {
    if (callback === null) {
      callback = (resp) => {}
    }
    return await axios.get(url, {
      param
    }).then((response) => {
      callback(response)
    }).catch(reason => {
      app.$message.error('Cannot get api: ' + url)
    })
  },
  async post (url, param, callback, error, app) {
    console.log('Post: ' + url)
    console.log(param)
    let resp = ''
    if (callback === null) {
      callback = (response) => {}
    }
    if (error == null) {
      error = (response) => {}
    }
    return await axios.post(url, param, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then((response) => {
      console.log(response)
      common.resp = response
      callback(response)
    }).catch(reason => {
      app.$message.error('Cannot post api: ' + url)
      error(reason)
    })
  }
}

export default methods
